package com.jml.生产者确认消息发送成功;

import com.jml.rabbitmq.RabbitMQConnection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


public class Producer {
    private static final String QUEUE_NAME = "jml-queue";

    /**
     * 生产者消息确认机制
     */
    public static void main(String[] args) {
        try {
            //1.创建一个新连接
            Connection connection = RabbitMQConnection.getConnection();
            //2.设置channel
            Channel channel = connection.createChannel();
            //3.发送消息
            String msg = "jml6666";
            //同步:confirm机制,会影响接口的吞吐量,代码会阻塞
            channel.confirmSelect();
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
            boolean result = channel.waitForConfirms();
            if (result) {
                System.out.println("消息投递成功");
            } else {
                System.out.println("消息投递失败");
            }
            channel.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * rabbitmq事务消息
     */
    public static void main002(String[] args) throws IOException, TimeoutException {
        //1.创建一个新连接
        Connection connection = RabbitMQConnection.getConnection();
        //2.设置channel
        Channel channel = connection.createChannel();
        try {
            //3.发送消息
            String msg = "jml6666";
            channel.txSelect();
            channel.basicPublish("", QUEUE_NAME, null, msg.getBytes());
            int i = 1 / 0;
            channel.txCommit();
            System.out.println("消息投递成功");
            channel.close();
            connection.close();
        } catch (Exception e) {
           if (channel != null) {
               // 回滚
               channel.txRollback();
           }
            e.printStackTrace();
        }
    }
}
